#include "StdAfx.h"
#include "XmlWrapper.h"
#include "GFileUtil.h"

#include <cassert>


XmlWrapper::XmlWrapper( const char* filePath ):
_depth( 0 )
{
	_valid = GFileUtil::readTextFile( filePath, _text );
	if( _valid ){
		_doc.Parse( _text.c_str() );
		_currentNode = _doc.FirstChild();
		// Skip the XML head
		nextSibling();
		assert( _currentNode != 0 );
	}
}


XmlWrapper::~XmlWrapper()
{
}

const char* XmlWrapper::getNodeType() const {
	return _currentNode->Value();
}

const char* XmlWrapper::getNodeValue() const {
	TiXmlNode* child = _currentNode->FirstChild();
	if( !child )
		return 0;
	TiXmlText * text = child->ToText();
	if( !text )
		return 0;
	return text->Value();
}

const char* XmlWrapper::getAttrValue( const char* attrName ) const {
	TiXmlElement* element = _currentNode->ToElement();
	if( !element )
		return 0;
	return element->Attribute( attrName );
}

bool XmlWrapper::firstChild(){
	TiXmlNode* child = _currentNode->FirstChild();
	if( !child )
		return false;
	_currentNode = child;
	++_depth;
	return true;
}

bool XmlWrapper::nextSibling(){
	for( TiXmlNode* next = _currentNode->NextSibling(); next; next = next->NextSibling() ){
		if( next->ToComment() )
			continue;
		else{
			_currentNode = next;
			return true;
		}
	}
	return false;
}

bool XmlWrapper::parent(){
	if( _depth == 0 )
		return false;
	_currentNode = _currentNode->Parent();
	--_depth;
	return true;
}
